package cn.tedu.tourism.passenger.controller;

import cn.tedu.tourism.base.response.JsonResult;
import cn.tedu.tourism.passenger.pojo.dto.PassengerParam;
import cn.tedu.tourism.passenger.pojo.vo.PassengerVO;
import cn.tedu.tourism.passenger.service.PassengerService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/v1/passenger/")
@Api(tags = "旅客管理")
@Slf4j
public class PassengerController {
    @Autowired
    private PassengerService passengerService;

    /**
     * 根据用户id查询旅客信息
     * @param userId
     * @return
     */
    @GetMapping("select/{userId}")
    public JsonResult selectByUserId(@PathVariable Long userId){
        log.debug("查询旅客信息：{}",userId);
        List<PassengerVO> list = passengerService.selectByUserId(userId);
        return JsonResult.ok(list);
    }

    /**
     * 保存旅客信息
     * @param passengerParam
     * @return
     */
    @PostMapping("save")
    public JsonResult save(@Valid PassengerParam passengerParam, BindingResult bindingResult){
        log.debug("保存旅客信息：{}",passengerParam);
        if (bindingResult.hasErrors()) {
            Map<String, Object> errors = new HashMap<>();
            bindingResult.getFieldErrors().forEach(error -> {
                errors.put(error.getField(), error.getDefaultMessage());
            });
            log.debug("参数校验失败：{}", errors);
            return JsonResult.ok(errors);
        }
        passengerService.save(passengerParam);
        return JsonResult.ok();
    }

    /**
     * 根据旅客id查询旅客详细信息
     * @param id
     * @return
     */
    @GetMapping("selectById/{id}")
    public JsonResult selectById(@PathVariable Long id){
        log.debug("查询旅客详细信息：{}",id);
        List<PassengerVO> list = passengerService.selectById(id);
        return JsonResult.ok(list);
    }

    /**
     * 删除旅客信息
     * @param id
     * @return
     */
    @PostMapping("delete/{id}")
    public JsonResult delete(@PathVariable Long id){
        log.debug("删除旅客信息：{}",id);
        passengerService.delete(id);
        return JsonResult.ok();
    }
}
